/*
 * Copyright © 2010 Breachwalls & Company Inc. and other authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.breachwalls.h2p.platform.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.breachwalls.h2p.platform.persistence.dao.ApprovalHospitalDao;
import com.breachwalls.h2p.platform.persistence.dao.ApprovalPharmacyDao;
import com.breachwalls.h2p.platform.persistence.dao.PermissionDao;
import com.breachwalls.h2p.platform.persistence.dao.UserDao;
import com.breachwalls.h2p.platform.persistence.entity.Hospital;
import com.breachwalls.h2p.platform.persistence.entity.Permission;
import com.breachwalls.h2p.platform.persistence.entity.Pharmacy;
import com.breachwalls.h2p.platform.persistence.entity.User;
import com.breachwalls.h2p.platform.security.LoginUser;
import com.breachwalls.h2p.platform.service.AuthenticationService;

/**
 * ユーザー認証サービスの実装.
 * @author Ken Todoroki
 * @version $Revision$
 */
public class UserDetailsServiceImpl implements AuthenticationService, UserDetailsService {

    private UserDao userDao;

    private PermissionDao permissionDao;

    private ApprovalHospitalDao approvalHospitalDao;

    private ApprovalPharmacyDao approvalPharmacyDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setPermissionDao(PermissionDao permissionDao) {
        this.permissionDao = permissionDao;
    }

    public void setApprovalHospitalDao(ApprovalHospitalDao approvalHospitalDao) {
        this.approvalHospitalDao = approvalHospitalDao;
    }

    public void setApprovalPharmacyDao(ApprovalPharmacyDao approvalPharmacyDao) {
        this.approvalPharmacyDao = approvalPharmacyDao;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,
            DataAccessException {
        // 未入力はエラー
        if (username == null || username.length() == 0) {
            throw new UsernameNotFoundException("Username is empty.");
        }

        return authorize(username);
    }

    public UserDetails authorize(String username) {
        // 認証する
        User u = userDao.findByUsername(username);
        if (u == null) {
            throw new UsernameNotFoundException("User[" + username + "] is not found.");
        }

        // ユーザーの役割を取得して、機能認可する
        List<Permission> permissions = permissionDao.findByUserId(u.getId());
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (Permission permission : permissions) {
            authorities.add(new GrantedAuthorityImpl(permission.getRole()));
        }

        // 参照可能病院の取得
        List<Hospital> hospitals = approvalHospitalDao.findHospitalsByUserId(u.getId());

        // 参照可能薬局の取得
        List<Pharmacy> pharmacies = approvalPharmacyDao.findPharmaciesByUserId(u.getId());

        LoginUser l = new LoginUser(username, u.getPassword(), true, true, true, true, authorities);
        l.setLogicalUserId(u.getId());
        l.setName(u.getUsername());
        // TODO 参照範囲をどう制限するか
        return l;
    }

}
